package com.example.javaproject.datastructure.queue;

/**
 * Description:单向循环队列
 * <br>Author：tian
 * <br>Time: 2019/3/11 17:46
 */
public class MyQueue {
    private Object[] queArray;
    private int maxSize;
    /**
     * 队列头部指针
     */
    private int front;
    /**
     * 队列尾部指针
     */
    private int rear;

    /**
     * 队列中实际元素数目
     */
    private int nItems;

    public MyQueue(int size) {
        this.maxSize = size;
        queArray = new Object[maxSize];
        front = 0;
        rear = -1;
    }

    public boolean isFull() {
        return nItems == maxSize;
    }

    public boolean isEmpty() {
        return nItems == 0;
    }


    public void insert(int s) {
        if (isFull()) {
            System.out.println("队列已满！！");
            return;
        }

        //如果队尾指针到顶了，那么循环回来重置为-1，执行队列的第一个元素
        if (rear == maxSize - 1) {
            rear = -1;
        }

        queArray[++rear] = s;
        nItems++;
    }

    /**
     * 移除数据
     */
    public Object remove() {
        Object removeValue = null;

        if (!isEmpty()) {
            removeValue = queArray[front];
            front++;

            if (front == maxSize) {
                front = 0;
            }
            nItems--;
            return removeValue;
        }
        return null;
    }

    /**
     * 获取队头数据
     *
     * @return
     */
    public Object peekFront() {
        return queArray[front];
    }

    /**
     * 获取队列大小
     *
     * @return
     */
    public int getSize() {
        return nItems;
    }

    public static void main(String[] args) {
        MyQueue queue = new MyQueue(3);
        queue.insert(1);
        queue.insert(2);
        queue.insert(3);//queArray数组数据为[1,2,3]

        System.out.println(queue.peekFront()); //1
        queue.remove();//queArray数组数据为[null,2,3]
        System.out.println(queue.peekFront()); //2

        queue.insert(4);//queArray数组数据为[4,2,3]
        queue.insert(5);//队列已满,queArray数组数据为[4,2,3]
    }
}
